# -- coding: utf-8 --

import sys
import time
import webbrowser

import win32clipboard as clipboard
import win32con
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtWidgets import QApplication, QDesktopWidget, QMainWindow
from system_hotkey import SystemHotkey

from main_fram import Ui_main_form
from tools.key import KeyBorder
from tools.my_tools import Thread, Timer
from tools.rq_data import decoder, update_or_not


class common_ipc(QMainWindow, Ui_main_form):
    # 定义一个热键信号
    sig_keyhot = pyqtSignal(str)

    def __init__(self):

        # 1. 简单的绘制一个窗口

        self.OrbTrans = {'混沌石': 'chaos', '幻色石': 'chrom', '改造石': 'alt', '重铸石': 'scour', '点金石': 'alch', '后悔石': 'regret',
                         '链接石': 'fuse', '神圣石': 'divine', '机会石': 'chance', '珠宝匠的棱镜': 'gcp', '瓦尔宝珠': 'vaal', '工匠石': 'jew'}

        self.version = 'v1.1'
        super(common_ipc, self).__init__()
        self.setupUi(self)
        try:
            url = update_or_not(self.version)
            if url is not None:
                self.tbw_update.setText("版本已更新, 请去\n%s 下载, 或者加QQ群:975332215" % url)
            else:
                self.tbw_update.setText("当前已是最新版本！")
        except:
            self.tbw_update.setText("版本更新检查失败！")

        # self.ltw_price.add_item(('40 chaos', '100', '1小时前'))
        self.decoder = decoder()
        self.keyBorder = KeyBorder()
        self.init_combobox()
        # 2. 设置我们的自定义热键响应函数
        self.sig_keyhot.connect(self.key_press_event)
        self.btn_open_in_web.clicked.connect(self.open_web)
        # 3. 初始化两个热键
        self.hk_start, self.hk_stop = SystemHotkey(), SystemHotkey()
        # 4. 绑定快捷键和对应的信号发送函数
        self.hk_start.register(('control', 'd'), callback=lambda x: self.send_key_event("start"))
        # self.hk_stop.register(('control', '2'), callback=lambda x: self.send_key_event("stop"))
        
        self.center()
        self.search_thread = Thread(self.search)
        # self.search_thread.finished.connect(self.start_timer)
        self.search_exa_timer = Timer(self.search_exa, 12000)
        # self.search_exa_timer.start()

    def start_timer(self):
        self.search_exa_timer.start()

    # 热键处理函数
    def center(self):
        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move(int((screen.width() - size.width()) / 2), 0)

    def open_web(self):
        print(self.decoder.searcher.web_url)
        webbrowser.open(self.decoder.searcher.web_url)


    def key_press_event(self, i_str):
        self.ltw_price.clear()
        self.ltw_price.add_item('查询中......')
        # time.sleep(0.05)
        # self.keyBorder.key_up('d')
        # time.sleep(0.05)
        # self.keyBorder.key_up('ctrl')
        # time.sleep(0.05)
        # self.keyBorder.key_down_up_team('ctrl', 'c')
        # self.search_exa_timer.stop()
        self.search_thread.start()
        self.showMinimized()
        self.showNormal()

    # 热键信号发送函数(将外部信号，转化成qt信号)
    def send_key_event(self, i_str):
        self.sig_keyhot.emit(i_str)

    @staticmethod
    def get_clipboard_text():
        clipboard.OpenClipboard()
        text = clipboard.GetClipboardData(win32con.CF_TEXT)
        clipboard.CloseClipboard()
        return text.decode('GBK')

    def search(self):
        try:
            target_str = self.get_clipboard_text()
        except:
            self.ltw_price.add_item("剪贴板打开失败, 请按 CTRL+D 重试")
            return

        ret = self.decoder.decode_and_search(target_str)
        self.ltw_price.clear()
        if ret == "锁IP":
            self.ltw_price.add_item("因查价太频繁，已暂时被交易网站锁IP")
            self.ltw_price.add_item("请1-2小时后重试")
            return

        if ret == "暂不支持":
            self.ltw_price.add_item("暂不支持当前物品查找")
            # QMessageBox.warning(self, '提示', '暂不支持当前物品查找', QMessageBox.Yes)
            return
        if not ret: 
            self.ltw_price.add_item("无数据返回！请按 CTRL+D 重试！")
            self.ltw_price.add_item("原因可能是版本过低、网络环境差、交易网站崩溃或市集无货")
            return

        self.ltw_price.add_item('价格')
        for price in ret:
            self.ltw_price.add_item(price)

    def init_combobox(self):
        # self.cbx_orb.setEditable(True)
        self.cbx_orb.addItems(self.OrbTrans.keys())
        self.cbx_server.addItem("S%s赛季" % self.decoder.searcher.season_num)
        self.cbx_server.addItem("S%s神赐" % self.decoder.searcher.season_num)
        self.cbx_server.addItem("永久区")
        if self.decoder.searcher.with_shanhui:
            self.cbx_server.addItem("闪回区")
        self.cbx_server.currentIndexChanged.connect(self.orb_changed_event)
        self.cbx_orb.currentIndexChanged.connect(self.server_changed_event)

    def server_changed_event(self):
        ui.search_exa_timer.thread.start()

    def orb_changed_event(self):
        server = self.cbx_server.currentText()
        self.decoder.searcher.server_change(server)

    def search_exa(self):
        text = self.cbx_orb.currentText()
        money = self.OrbTrans[text]
        priceList = self.decoder.searcher.search('崇高石', kind=3, money=money, web_update = False)
        if priceList == [] or priceList[0] == '':
            self.lab_exo.setText("EX = 无")
        else:
            price = priceList[int(len(priceList) / 2)].split()[1]
            self.lab_exo.setText("EX = %s" % price)

if __name__ == "__main__":
    qss_style = """
        QPushButton {
            color: green;
            border-color: blueviolet;
            background-color: black;
        };
    }
    """
    app = QApplication(sys.argv)

    ui = common_ipc()
    # ui.setStyleSheet(qss_style)
    ui.show()
    ui.search_exa_timer.thread.start()
    sys.exit(app.exec_())
